package com.mairuide.platmanager;

import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.hibernate.SQLQuery;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mairuide._frame.base.BaseRepository;
import com.mairuide._frame.base.BaseServiceProxy;
import com.mairuide._frame.base.Constant;
import com.mairuide._frame.utils.StringUtils;
import com.mairuide._frame.utils.Testtrans;
import com.mairuide._frame.utils.Tools;
import com.mairuide.datalog.ActionType;
import com.mairuide.datalog.DataOperationLogService;
import com.mairuide.datalog.ModuleFlag;
import com.mairuide.datalog.SystemFlag;
import com.mairuide.platgroupuser.PlatGroupUser;
import com.mairuide.platgroupuser.PlatGroupUserService;
import com.mairuide.platrole.PlatRole;
import com.mairuide.platrole.PlatRoleService;
import com.mairuide.platroleuser.PlatRoleUser;
import com.mairuide.platroleuser.PlatRoleUserService;


@Service
@Transactional(readOnly=true)
public class PlatManagerService extends BaseServiceProxy<PlatManager> {
	
	@Resource
	private EntityManager em;
	
	@Resource
	private PlatManagerRepository platManagerRepository;
	
	@Resource
	private DataOperationLogService dataOperationLogService;
	
	@Resource
	private PlatRoleService platRoleService;
	
	@Resource
	private PlatRoleUserService platRoleUserService;
	
	@Resource
	private PlatGroupUserService platGroupUserService;
	
	@Override
	protected BaseRepository<PlatManager> getBaseRepository() {
		return platManagerRepository;
	}
	
	@Override
	protected EntityManager getEntityManager() {
		return em;
	}
	
	/**
	 * 根据登录名查询（登录用）
	 * @param loginName
	 * @return
	 */
	public PlatManager findByLoginName(String loginName) {
		return platManagerRepository.findTop1ByLoginName(loginName);
	}
	
	/**
	 * 根据主键集合，查询一批用户对象（关联用）
	 * @param ids
	 * @return
	 */
	public List<PlatManager> findByIdIn(Collection<Integer> ids){
		Iterator<Integer> iterator = ids.iterator();
		while (iterator.hasNext()) {
			Integer id = iterator.next();
			if(id == null) {
				iterator.remove();
			}
		}
		return platManagerRepository.findByIdIn(ids);
	}
	
	/**
	 * 根据角色查询平台用户信息
	 * @param roleCode
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<PlatManager> findByRoleCode(String roleCode){
		if(StringUtils.isEmpty(roleCode)) {
			throw new RuntimeException("roleCode is null");
		}
		List<Object> params = new LinkedList<Object>();
		StringBuffer fromWhereSql = new StringBuffer();
		fromWhereSql.append("FROM tb_plat_manager pm ");
		fromWhereSql.append("INNER JOIN tb_plat_role_user pru ON pru.user_id = pm.id AND pm.state = 100 ");
		fromWhereSql.append("INNER JOIN tb_plat_role pr ON pr.role_id = pru.role_id AND pr.role_code = ? AND pm.state = 100 ");
		params.add(roleCode);
		
		StringBuffer selectSql = new StringBuffer();
		selectSql.append("SELECT pm.id AS id, pm.login_name AS loginName, pm.nick_name AS nickName, pm.agent_sale_id AS agentSaleId, pm.agent_sale_name AS agentSaleName ");
		selectSql.append(", pm.superior_id AS superiorId, pm.account_manager_id AS accountManagerId, pm.account_manager_name AS accountManagerName ");
		
		String orderBySql = "ORDER BY pm.id DESC ";
		
		Query contentQuery = em.createNativeQuery(selectSql + fromWhereSql.toString() + orderBySql);
		if (!params.isEmpty()) {
			for (int i = 0; i < params.size(); i++) {
				contentQuery.setParameter(i+1, params.get(i));
			}
		}
		contentQuery.unwrap(SQLQuery.class).setResultTransformer(new Testtrans(PlatManager.class));
		return contentQuery.getResultList();
		
	}
	
	/**
	 * @param state
	 * @return
	 */
	public List<PlatManager> findByState(Integer state){
		return platManagerRepository.findByState(state);
	}
	
	/**
	 * 验证登录名唯一
	 * @param id 主键
	 * @param loginName 登录名
	 * @return
	 */
	public PlatManager verifyRepeatByIdAndLoginName(Integer id, String loginName) {
		StringBuffer hql = new StringBuffer();
		hql.append("FROM PlatManager WHERE loginName = :loginName ");
		if (id != null) {
			hql.append("AND id != :id ");
		}
		Query query = em.createQuery(hql.toString());
		query.setParameter("loginName", loginName);
		if (id != null) {
			query.setParameter("id", id);
		}
		query.setMaxResults(1);
		PlatManager platManager = null;
		try {
			platManager =(PlatManager) query.getSingleResult();
		} catch (NoResultException nre) {
			
		}
		return platManager;
	}
	
	/**
	 * 新增子账号
	 * @param subAccount
	 * @param userType 用户分类  在列表查询时获得（1:代理商角色,2:运营中心部门,3:总部或总部下级部门）
	 * @param roleIds
	 * @param groupIds
	 * @param loginUser
	 * @throws Exception
	 */
	@Transactional(readOnly=false)
	public void saveSubAccount(PlatManager subAccount, Integer userType
			, int[] roleIds, int[] groupIds, PlatManager loginUser) throws Exception {
		
		subAccount.setCreateId(loginUser.getId());
		subAccount.setCreaterName(loginUser.getNickName());
		subAccount.setCreateTime(new Date());
		
		Md5PasswordEncoder md5 = new Md5PasswordEncoder();
		String password = md5.encodePassword(Constant.PLATMANAGER_DEFAULT_PASSWORD, null);
		subAccount.setPassword(password);
		
		subAccount = platManagerRepository.save(subAccount);
		
		// 保存角色和部门。这里一个人只保存一个部门， 一个人只保存一个角色
		this.saveRoleAndGroup(subAccount, userType, roleIds, groupIds, loginUser);
		
		// 添加日志
		dataOperationLogService.save(subAccount.getId().toString(), loginUser, subAccount, new PlatManager(), SystemFlag.ZD, ModuleFlag.PLATMANAGER, ActionType.ADD);
	}
	
	/**
	 * 私有方法-保存角色和部门
	 * @param subAccount
	 * @param userType
	 * @param roleIds
	 * @param groupIds
	 * @param loginUser
	 */
	private void saveRoleAndGroup (PlatManager subAccount, Integer userType
			, int[] roleIds, int[] groupIds, PlatManager loginUser) {
		// 保存角色和部门。这里一个人只保存一个部门， 一个人只保存一个角色
		if (userType == 1 || userType == 2) {
			// 保存到操作人所在的部门
			List<PlatGroupUser> platGroupUserList = platGroupUserService.findByUserId(loginUser.getId());
			if (platGroupUserList != null && !platGroupUserList.isEmpty()) {
				Integer groupId = platGroupUserList.get(0).getGroupId();
				PlatGroupUser platGroupUser = new PlatGroupUser();
				platGroupUser.setGroupId(groupId);
				platGroupUser.setUserId(subAccount.getId());
				platGroupUserService.save(platGroupUser);
			}
			if (userType == 1) {
				// 保存代理商角色
				PlatRole platRole = platRoleService.findTop1ByRoleCode("AGENT");
				PlatRoleUser platRoleUser = new PlatRoleUser();
				platRoleUser.setRoleId(platRole.getRoleId());
				platRoleUser.setUserId(subAccount.getId());
				platRoleUserService.save(platRoleUser);
			} else {
				// 运营中心修改为运营中心角色
				PlatRole platRole = platRoleService.findTop1ByRoleCode("OPERATION_CENTER");
				PlatRoleUser platRoleUser = new PlatRoleUser();
				platRoleUser.setRoleId(platRole.getRoleId());
				platRoleUser.setUserId(subAccount.getId());
				platRoleUserService.save(platRoleUser);
			}
		} else if (userType == 3) {
			// 保存到所选的部门
			PlatGroupUser platGroupUser = new PlatGroupUser();
			platGroupUser.setGroupId(groupIds[0]);
			platGroupUser.setUserId(subAccount.getId());
			platGroupUserService.save(platGroupUser);
			
			// 保存所选的角色
			PlatRoleUser platRoleUser = new PlatRoleUser();
			platRoleUser.setRoleId(roleIds[0]);
			platRoleUser.setUserId(subAccount.getId());
			platRoleUserService.save(platRoleUser);
		}
	}
	
	/**
	 * 修改子账号
	 * @param subAccount
	 * @param userType
	 * @param roleIds
	 * @param groupIds
	 * @param loginUser
	 * @throws Exception
	 */
	@Transactional(readOnly=false)
	public void updateSubAccount(PlatManager subAccount, Integer userType
			, int[] roleIds, int[] groupIds, PlatManager loginUser) throws Exception {
		
		PlatManager oldSubAccount = platManagerRepository.findOne(subAccount.getId());
		PlatManager copySubAccount = Tools.beanCopyForLodBean(oldSubAccount);
		
		StringUtils.mergeObject(subAccount, oldSubAccount);
		
		oldSubAccount = platManagerRepository.save(oldSubAccount);
		
		// 先删除这个人的所有部门
		platGroupUserService.deleteByUserId(oldSubAccount.getId());
		// 先删除这个人的所有角色
		platRoleUserService.deleteByUserId(oldSubAccount.getId());
		
		// 保存角色和部门。这里一个人只保存一个部门， 一个人只保存一个角色
		this.saveRoleAndGroup(oldSubAccount, userType, roleIds, groupIds, loginUser);
		
		// 添加日志
		dataOperationLogService.save(oldSubAccount.getId().toString(), loginUser, oldSubAccount, copySubAccount, SystemFlag.ZD, ModuleFlag.PLATMANAGER, ActionType.MODIFY);
	}
	
	/**
	 * 新增代理商
	 * @param agent
	 * @param loginUser
	 * @throws Exception 
	 */
	@Transactional(readOnly=false)
	public void saveAgent(PlatManager platManager, PlatManager loginUser,Integer groupId) throws Exception {
		/* 默认密码 */
		Md5PasswordEncoder md5 = new Md5PasswordEncoder();
		String password = md5.encodePassword(Constant.PLATMANAGER_DEFAULT_PASSWORD, null);
		platManager.setPassword(password);
		platManager.setCreateId(loginUser.getId());
		platManager.setCreaterName(loginUser.getLoginName());
		platManager.setCreateTime(new Date());
		platManager.setSuperiorId(0);
		platManagerRepository.save(platManager);
		
		// 保存到所选的部门
		PlatGroupUser platGroupUser = new PlatGroupUser();
		platGroupUser.setGroupId(groupId);
		platGroupUser.setUserId(platManager.getId());
		platGroupUserService.save(platGroupUser);
		
		// 保存代理商角色
		PlatRole platRole = platRoleService.findTop1ByRoleCode("AGENT");
		PlatRoleUser platRoleUser = new PlatRoleUser();
		platRoleUser.setRoleId(platRole.getRoleId());
		platRoleUser.setUserId(platManager.getId());
		platRoleUserService.save(platRoleUser);
		// 添加日志
		dataOperationLogService.save(platManager.getId().toString(), loginUser, platManager, new PlatManager(), SystemFlag.ZD, ModuleFlag.PLATMANAGER, ActionType.ADD);
	}
	
	/**
	 * 修改代理商
	 * @param agent
	 * @param loginUser
	 * @throws Exception 
	 */
	@Transactional(readOnly=false)
	public void updateAgent(PlatManager platManager, PlatManager loginUser, Integer groupId) throws Exception {
		
		PlatManager oldPlat = platManagerRepository.findOne(platManager.getId());
		PlatManager copyPlat = Tools.beanCopyForLodBean(oldPlat);
		
		StringUtils.mergeObject(platManager, oldPlat);
		
		platManagerRepository.save(oldPlat);
		// 保存到所选的部门
		// 先删除这个人的所有部门
		platGroupUserService.deleteByUserId(platManager.getId());
		PlatGroupUser platGroupUser = new PlatGroupUser();
		platGroupUser.setGroupId(groupId);
		platGroupUser.setUserId(platManager.getId());
		platGroupUserService.save(platGroupUser);
		// 添加日志
		dataOperationLogService.save(oldPlat.getId().toString(), loginUser, oldPlat, copyPlat, SystemFlag.ZD, ModuleFlag.PLATMANAGER, ActionType.MODIFY);
		
	}
	
	/**
	 * 用户管理-列表查询-总部
	 * @param keywordType
	 * @param keyword
	 * @param pageable
	 * @return
	 */
	public Page<PlatManager> findManagerList4HeadQuarter(Integer keywordType, String keyword, Pageable pageable) {
		
		List<Object> params = new LinkedList<Object>();
		StringBuffer fromWhereSql = new StringBuffer();
		fromWhereSql.append("FROM tb_plat_manager pm ");
		fromWhereSql.append("INNER JOIN tb_plat_group_user pgu ON pgu.user_id = pm.id AND (pm.is_sub_account IS NULL OR pm.is_sub_account = 0) ");
		fromWhereSql.append("INNER JOIN tb_plat_group pg ON pg.group_id = pgu.group_id AND pg.group_code LIKE 'HEADQUARTERS%' ");
		fromWhereSql.append(appendWhere(keywordType, keyword, params));
		
		StringBuffer selectSql = new StringBuffer();
		selectSql.append("SELECT pm.id AS id, pm.login_name AS loginName, pm.nick_name AS nickName ");
		selectSql.append(", pm.superior_id AS superiorId, pm.phone AS phone, pm.state AS state ");
		
		String orderBySql = "ORDER BY pm.id DESC ";
		
		// 封装并返回
		return super.findPageBySql(PlatManager.class, selectSql.toString(), fromWhereSql.toString(), orderBySql, params, pageable);
	}
	
	/**
	 * 用户管理-列表查询-运营中心
	 * @param superiorId 上级ID
	 * @param keywordType
	 * @param keyword
	 * @param pageable
	 * @return
	 */
	public Page<PlatManager> findManagerList4OperationCenter(Integer superiorId, Integer keywordType, String keyword, Pageable pageable) {
		
		List<Object> params = new LinkedList<Object>();
		StringBuffer fromWhereSql = new StringBuffer();
		fromWhereSql.append("FROM tb_plat_manager pm ");
		fromWhereSql.append("INNER JOIN tb_plat_group_user pgu ON pgu.user_id = pm.id AND pm.is_sub_account = 1 AND pm.superior_id = ? ");
		params.add(superiorId);
		fromWhereSql.append("INNER JOIN tb_plat_group pg ON pg.group_id = pgu.group_id AND pg.group_code LIKE 'OPERATIONS_CENTER%' ");
		fromWhereSql.append(appendWhere(keywordType, keyword, params));
		
		StringBuffer selectSql = new StringBuffer();
		selectSql.append("SELECT pm.id AS id, pm.login_name AS loginName, pm.nick_name AS nickName ");
		selectSql.append(", pm.superior_id AS superiorId, pm.phone AS phone, pm.state AS state ");
		
		String orderBySql = "ORDER BY pm.id DESC ";
		
		// 封装并返回
		return super.findPageBySql(PlatManager.class, selectSql.toString(), fromWhereSql.toString(), orderBySql, params, pageable);
	}
	
	/**
	 * 用户管理-列表查询-代理商
	 * @param superiorId 上级ID
	 * @param keywordType
	 * @param keyword
	 * @param pageable
	 * @return
	 */
	public Page<PlatManager> findManagerList4Agent(Integer superiorId, Integer keywordType, String keyword, Pageable pageable) {
		
		List<Object> params = new LinkedList<Object>();
		StringBuffer fromWhereSql = new StringBuffer();
		fromWhereSql.append("FROM tb_plat_manager pm ");
		fromWhereSql.append("INNER JOIN tb_plat_role_user pru ON pru.user_id = pm.id AND pm.is_sub_account = 1 AND pm.superior_id = ? ");
		params.add(superiorId);
		fromWhereSql.append("INNER JOIN tb_plat_role pr ON pr.role_id = pru.role_id AND pr.role_code = 'AGENT' ");
		fromWhereSql.append(appendWhere(keywordType, keyword, params));
		
		StringBuffer selectSql = new StringBuffer();
		selectSql.append("SELECT pm.id AS id, pm.login_name AS loginName, pm.nick_name AS nickName ");
		selectSql.append(", pm.superior_id AS superiorId, pm.phone AS phone, pm.state AS state ");
		
		String orderBySql = "ORDER BY pm.id DESC ";
		
		// 封装并返回
		return super.findPageBySql(PlatManager.class, selectSql.toString(), fromWhereSql.toString(), orderBySql, params, pageable);
	}
	
	/**
	 * WHERE SQL append
	 * @param keywordType
	 * @param keyword
	 * @param params
	 * @return
	 */
	private String appendWhere(Integer keywordType, String keyword, List<Object> params) {
		StringBuffer sql = new StringBuffer();
		
		if(keywordType == 1 && StringUtils.isNotEmpty(keyword)) {
			sql.append("AND nick_name = ? ");
			params.add(keyword);
		}
		if(keywordType == 2 && StringUtils.isNotEmpty(keyword)) {
			sql.append("AND login_name = ? ");
			params.add(keyword);
		}
		
		if(keywordType == 0 && StringUtils.isNotEmpty(keyword)) {
			String nickName = keyword.trim();
			String loginName = keyword.trim();
			String whereOrSql = appendWhereOrSql(nickName, loginName, params);
			if (whereOrSql != null) {
				sql.append(whereOrSql);
			}
		}
		
		if (sql.length() > 0) {
			sql.delete(0, "AND ".length());
			sql.insert(0, "WHERE ");
		}
		
		return sql.toString();
	}
	
	/**
	 * 关键字OR拼接
	 * @param nickName
	 * @param loginName
	 * @param params
	 * @return
	 */
	private String appendWhereOrSql(String nickName, String loginName, List<Object> params) {
		
		StringBuffer sql = new StringBuffer();
		
		if (StringUtils.isNotEmpty(nickName)) {
			sql.append("OR nick_name LIKE ? ");
			params.add("%"+nickName+"%");
		}
		if (StringUtils.isNotEmpty(loginName)) {
			sql.append("OR login_name LIKE ? ");
			params.add("%"+loginName+"%");
		}
		
		if (sql.length() > 0) {
			sql.delete(0, "OR ".length());
		}
		if (sql.length() > 0) {
			return "AND ("+sql.toString()+") ";
		}else {
			return null;
		}
	}
	
	/**
	 * 代理商查询(运营中心用)
	 * @param pageable
	 * @param searchKey
	 * @param superiorId
	 * @return
	 */
	public Page<PlatManager> findAgent4OperationCenter(Pageable pageable, String searchKey, Integer groupId) {
		
		List<Object> params = new LinkedList<Object>();
		StringBuffer fromWhereSql = new StringBuffer();
		fromWhereSql.append("FROM tb_plat_manager pm ");
		fromWhereSql.append("INNER JOIN tb_plat_role_user pru ON pru.user_id = pm.id AND pm.state = 100 AND (pm.is_sub_account IS NULL OR pm.is_sub_account = 0) ");
		fromWhereSql.append("INNER JOIN tb_plat_role pr ON pr.role_id = pru.role_id AND pr.role_code = 'AGENT' ");
		fromWhereSql.append("INNER JOIN tb_plat_group_user pgu ON pgu.user_id = pm.id AND pgu.group_id = ? ");
		params.add(groupId);
		if (StringUtils.isNotEmpty(searchKey)) {
			fromWhereSql.append("WHERE pm.nick_name like ? OR pm.login_name like ? ");
			params.add("%"+searchKey.trim()+"%");
			params.add("%"+searchKey.trim()+"%");
		}
		StringBuffer selectSql = new StringBuffer();
		selectSql.append("SELECT pm.id AS id, pm.login_name AS loginName, pm.nick_name AS nickName ");
		selectSql.append(", pm.superior_id AS superiorId, pm.phone AS phone, pm.state AS state, account_manager_name as accountManagerName ");
		
		String orderBySql = "ORDER BY pm.id DESC ";
		
		// 封装并返回
		return super.findPageBySql(PlatManager.class, selectSql.toString(), fromWhereSql.toString(), orderBySql, params, pageable);
	}
	
	
	/**
	 * 查询所有角色是代理商，且不是子账号的数据(总部查询代理商)
	 * @param superiorId
	 * @param keywordType
	 * @param keyword
	 * @param pageable
	 * @return
	 */
	public Page<PlatManager> findHqAgentList(Integer keywordType, String keyword, Pageable pageable) {
		
		List<Object> params = new LinkedList<Object>();
		StringBuffer fromWhereSql = new StringBuffer();
		fromWhereSql.append("FROM tb_plat_manager pm ");
		fromWhereSql.append("INNER JOIN tb_plat_role_user pru ON pru.user_id = pm.id AND pm.state = 100 AND (pm.is_sub_account IS NULL OR pm.is_sub_account = 0) ");
		fromWhereSql.append("INNER JOIN tb_plat_role pr ON pr.role_id = pru.role_id AND pr.role_code = 'AGENT' ");
		fromWhereSql.append(appendWhere(keywordType, keyword, params));
		
		StringBuffer selectSql = new StringBuffer();
		selectSql.append("SELECT pm.id AS id, pm.login_name AS loginName, pm.nick_name AS nickName ");
		selectSql.append(", pm.superior_id AS superiorId, pm.phone AS phone, pm.state AS state ");
		
		String orderBySql = "ORDER BY pm.id DESC ";
		
		// 封装并返回
		return super.findPageBySql(PlatManager.class, selectSql.toString(), fromWhereSql.toString(), orderBySql, params, pageable);
	}
	
	/**
	 * 查询代理商下的内部员工
	 * @param agentId 代理商ID
	 * @return
	 */
	public List<PlatManager> findInnerUser4Agent(Integer agentId) {
		List<Object> params = new LinkedList<Object>();
		StringBuffer fromWhereSql = new StringBuffer();
		fromWhereSql.append("FROM tb_plat_manager pm ");
		fromWhereSql.append("INNER JOIN tb_plat_role_user pru ON pru.user_id = pm.id AND pm.state = 100 AND pm.is_sub_account = 1 AND pm.superior_id = ? ");
		fromWhereSql.append("INNER JOIN tb_plat_role pr ON pr.role_id = pru.role_id AND pr.role_code = 'AGENT' ");
		params.add(agentId);
		
		StringBuffer selectSql = new StringBuffer();
		selectSql.append("SELECT pm.id AS id, pm.login_name AS loginName, pm.nick_name AS nickName ");
		
		String orderBySql = "ORDER BY pm.id DESC ";
		
		// 封装并返回
		return super.findListBySql(PlatManager.class, selectSql.toString(), fromWhereSql.toString(), orderBySql, params);
	}
	
	/**
	 * 查询某个运营中心下的内部员工
	 * @param groupId 所在运营中心的部门ID
	 * @param superiorId 上级ID
	 * @return
	 */
	public List<PlatManager> findInnerUser4OperationCenter(Integer groupId, Integer superiorId) {
		List<Object> params = new LinkedList<Object>();
		StringBuffer fromWhereSql = new StringBuffer();
		fromWhereSql.append("FROM tb_plat_manager pm ");
		fromWhereSql.append("INNER JOIN tb_plat_role_user pru ON pru.user_id = pm.id AND pm.state = 100 AND pm.is_sub_account = 1 AND pm.superior_id = ? ");
		fromWhereSql.append("INNER JOIN tb_plat_role pr ON pr.role_id = pru.role_id AND pr.role_code = 'OPERATION_CENTER' ");
		fromWhereSql.append("INNER JOIN tb_plat_group_user pgu ON pgu.user_id = pm.id AND pgu.group_id = ? ");
		params.add(superiorId);
		params.add(groupId);
		
		StringBuffer selectSql = new StringBuffer();
		selectSql.append("SELECT pm.id AS id, pm.login_name AS loginName, pm.nick_name AS nickName ");
		
		String orderBySql = "ORDER BY pm.id DESC ";
		
		// 封装并返回
		return super.findListBySql(PlatManager.class, selectSql.toString(), fromWhereSql.toString(), orderBySql, params);
	}
	
	/**
	 * 查询总部下的内部员工(没有显示直接在总部下的人员)
	 * @return
	 */
	public List<PlatManager> findInnerUser4HeadQuarter() {
		List<Object> params = new LinkedList<Object>();
		StringBuffer fromWhereSql = new StringBuffer();
		fromWhereSql.append("FROM tb_plat_manager pm ");
		fromWhereSql.append("INNER JOIN tb_plat_group_user pgu ON pgu.user_id = pm.id AND pm.state = 100 ");
		fromWhereSql.append("INNER JOIN tb_plat_group pg ON pg.group_id = pgu.group_id AND pg.group_code LIKE 'HEADQUARTERS_%' ");
		
		StringBuffer selectSql = new StringBuffer();
		selectSql.append("SELECT pm.id AS id, pm.login_name AS loginName, pm.nick_name AS nickName ");
		
		String orderBySql = "ORDER BY pm.id DESC ";
		
		// 封装并返回
		return super.findListBySql(PlatManager.class, selectSql.toString(), fromWhereSql.toString(), orderBySql, params);
	}
	
	/**
	 * 查询总部下的代理商管理员(非子账号代理商)
	 * @return
	 */
	public List<PlatManager> findAgentManager4HeadQuarter() {
		List<Object> params = new LinkedList<Object>();
		StringBuffer fromWhereSql = new StringBuffer();
		fromWhereSql.append("FROM tb_plat_manager pm ");
		fromWhereSql.append("INNER JOIN tb_plat_role_user pru ON pru.user_id = pm.id AND pm.state = 100 AND (pm.is_sub_account IS NULL OR pm.is_sub_account = 0) ");
		fromWhereSql.append("INNER JOIN tb_plat_role pr ON pr.role_id = pru.role_id AND pr.role_code = 'AGENT' ");
		fromWhereSql.append("INNER JOIN tb_plat_group_user pgu ON pgu.user_id = pm.id ");
		fromWhereSql.append("INNER JOIN tb_plat_group pg ON pg.group_id = pgu.group_id AND pg.group_code LIKE 'HEADQUARTERS%' ");
		
		StringBuffer selectSql = new StringBuffer();
		selectSql.append("SELECT pm.id AS id, pm.login_name AS loginName, pm.nick_name AS nickName ");
		
		String orderBySql = "ORDER BY pm.id DESC ";
		
		// 封装并返回
		return super.findListBySql(PlatManager.class, selectSql.toString(), fromWhereSql.toString(), orderBySql, params);
	}
	
	/**
	 * 查询一个运营中心下的代理商管理员(非子账号代理商)
	 * @param groupId 运营中心部门ID
	 * @return
	 */
	public List<PlatManager> findAgentManager4OperationCenter (Integer groupId) {
		
		List<Object> params = new LinkedList<Object>();
		StringBuffer fromWhereSql = new StringBuffer();
		fromWhereSql.append("FROM tb_plat_manager pm ");
		fromWhereSql.append("INNER JOIN tb_plat_role_user pru ON pru.user_id = pm.id AND pm.state = 100 AND (pm.is_sub_account IS NULL OR pm.is_sub_account = 0) ");
		fromWhereSql.append("INNER JOIN tb_plat_role pr ON pr.role_id = pru.role_id AND pr.role_code = 'AGENT' ");
		fromWhereSql.append("INNER JOIN tb_plat_group_user pgu ON pgu.user_id = pm.id AND pgu.group_id = ? ");
		params.add(groupId);
		
		StringBuffer selectSql = new StringBuffer();
		selectSql.append("SELECT pm.id AS id, pm.login_name AS loginName, pm.nick_name AS nickName ");
		selectSql.append(", pm.superior_id AS superiorId, pm.phone AS phone, pm.state AS state ");
		
		String orderBySql = "ORDER BY pm.id DESC ";
		
		// 封装并返回
		return super.findListBySql(PlatManager.class, selectSql.toString(), fromWhereSql.toString(), orderBySql, params);
	}
	
	/**
	 * 查询一个运营中心管理员(非子账号代理商)
	 * @return
	 */
	public List<PlatManager> findOperationCenterManager () {
		
		List<Object> params = new LinkedList<Object>();
		StringBuffer fromWhereSql = new StringBuffer();
		fromWhereSql.append("FROM tb_plat_manager pm ");
		fromWhereSql.append("INNER JOIN tb_plat_group_user pgu ON pgu.user_id = pm.id AND pm.state = 100 AND (pm.is_sub_account IS NULL OR pm.is_sub_account = 0) ");
		fromWhereSql.append("INNER JOIN tb_plat_group pg ON pg.group_id = pgu.group_id AND pg.group_code LIKE 'OPERATIONS_CENTER%' ");
		fromWhereSql.append("INNER JOIN tb_plat_role_user pru ON pru.user_id = pm.id ");
		fromWhereSql.append("INNER JOIN tb_plat_role pr ON pr.role_id = pru.role_id AND pr.role_code <> 'AGENT' ");
		
		StringBuffer selectSql = new StringBuffer();
		selectSql.append("SELECT pm.id AS id, pm.login_name AS loginName, pm.nick_name AS nickName ");
		
		String orderBySql = "ORDER BY pm.id DESC ";
		
		// 封装并返回
		return super.findListBySql(PlatManager.class, selectSql.toString(), fromWhereSql.toString(), orderBySql, params);
	}
	
}
